// getdata.js

import { ref, onMounted, onBeforeUnmount, reactive } from "vue";
import * as mqtt from "mqtt/dist/mqtt.min";

export function useGetData(mqtt_config) {
  let realMessage = reactive({});
  let client = reactive({
    connected: false
  } as mqtt.MqttClient);
  const topics = mqtt_config.topics;
  const connection = reactive({
    // ws or wss
    protocol: import.meta.env.VITE_APP_MQTT_PROTOCOL as string,
    host: import.meta.env.VITE_APP_MQTT_HOST as string,
    clientId: "emqx_vue3_" + Math.random().toString(16).substring(2, 8),
    username: import.meta.env.VITE_APP_MQTT_USERNAME as string,
    password: import.meta.env.VITE_APP_MQTT_PASSWORD as string ,
    clean: true,
    connectTimeout: 30 * 1000, // ms
    reconnectPeriod: 4000 // ms
  });
  const subscription = ref({
    topic: "/analogData",
    qos: 0
  });
  // 在组件挂载时订阅 MQTT 数据
  onMounted(() => {
    const { protocol, host, ...options } = connection;
    console.log('===')
    console.log((import.meta.env.VITE_APP_MQTT_HOST as string))
    console.log(host)
    const url="ws://"+host+"/mqtt";

    client = mqtt.connect(url, options); // 替换成您的 MQTT 服务器地址
    client.on("connect", () => {
      console.log("Connected to MQTT broker");
      // 这里进行您的 MQTT 订阅操作
      for (const mid in topics) {
        client.subscribe(topics[mid], err => {
          if (!err) {
            console.log("Subscribed to topic");
          } else {
            console.error("Failed to subscribe to topic", err);
          }
        });
      }
    });
    client.on("reconnect", error => {
      console.log("正在重连:", error);
    });

    client.on("message", (topic, message) => {
      const parsedMessage = parseMessage(message);

      // 处理收到的消息
      realMessage[topic] = { topic, message: parsedMessage };
      // 可以根据需求对收到的数据进行处理
    });
  });
  function parseMessage(message: any) {
    const messageStr = message.toString();
    try {
      return JSON.parse(messageStr);
    } catch (e) {
      // messageStr is not JSON format, return it as is
      return messageStr;
    }
  }
  // 在组件卸载前取消 MQTT 订阅并断开连接
  onBeforeUnmount(() => {
    if (client) {
      client.unsubscribe(topics, err => {
        if (!err) {
          console.log("Unsubscribed from topic");
        } else {
          console.error("Failed to unsubscribe from topic", err);
        }
        client.end(); // 断开 MQTT 连接
      });
    }
  });

  return {
    realMessage
    // 返回其他可能需要的数据或方法
  };
}
